package org.caro.actions.play;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.caro.utils.Constants;
import org.caro.utils.Position;

public class SendPlayChess extends Thread {
	private Socket socket;
	private DataOutputStream dataOutputStream;
	private String host;
	private int port;
	private int mode;

	public SendPlayChess(String host, int port, int mode) {
		super("send play");
		this.host = host;
		this.port = port;
		this.mode = mode;
		start();
	}
	@Override
	public void run() {
		try {
			if (mode == Constants.HOST) {
				ServerSocket server = new ServerSocket(port);
				socket = server.accept();
				server.close();
			} else if (mode == Constants.CLIENT)
				socket = new Socket(host, port);
			dataOutputStream = new DataOutputStream(socket.getOutputStream());
		} catch (Exception ex) {
		}
	}

	public void doAction(Position position){
		try {
			String message = position.toString();
			for (int i = 0; i < message.length(); i++)
				dataOutputStream.write((byte) message.charAt(i));
			dataOutputStream.write(13);
			dataOutputStream.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void closeConnetion() throws Exception {
		dataOutputStream.close();
		socket.close();
	}
}
